import { TableColumn } from 'element-ui';
import {
  parseMinWidth,
} from 'element-ui/packages/table/src/util.js';
import { max, map, isEmpty, calStringWidth } from './util'

export default {
  name: 'ElTableColumn',
  extends: TableColumn, // 指定继承组件
  props: {
    fitByClass: {
      type: String,
      default: 'cell',
    },
    /**是否自定义排序 */
    customSort: {
      type: Boolean,
      default: false,
    },
    autoFit: {
      type: Boolean,
      default: true,
    },
    fitGap: {
      type: Number,
      default: 0,
    },
    fitHeader: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      autoWidth: 0,
    };
  },
  computed: {
    realMinWidth() {
      if (this.autoFit) {
        return parseMinWidth(max([this.minWidth, this.autoWidth]));
      }
      return TableColumn.computed?.realMinWidth.call(this)
    },
  },
  methods: {
    updateAutoWidth() {
      if (!this.autoFit) return

      const cellWrapperClass = this.fitHeader ? `.${this.columnId}` : `td.${this.columnId}`

      let cells = window.document.querySelectorAll(`${cellWrapperClass} .${this.fitByClass}`);

      if (isEmpty(cells)) {
        cells = window.document.querySelectorAll(`${cellWrapperClass} .cell`);
      }
      if (isEmpty(cells)) {
        return;
      }
      let propsData = this.$options.propsData;
      const autoMinWidth = max(map(cells, item => {
        // console.log(` ==>`, item.getBoundingClientRect());
        return calStringWidth(item.innerText, propsData)
      }))
      // console.log(`autoMinWidth ==>`, autoMinWidth);
      this.autoWidth = autoMinWidth
    },
  },
  updated() {
    this.updateAutoWidth();
  },
  mounted() {
    this.$nextTick(this.updateAutoWidth);
    this.$Bus.$on("tableDataChanged", (data) => {
      // console.log(`receive  tableDataChanged==>`, data);
      this.$nextTick(() => {
        // console.log(` ==>`, window.document.querySelectorAll(`.el-table_1_column_1`));
        // this.updateAutoWidth()
      })
    });
  },
};
